package com.yangquan.ayuan.deadLock;

import java.util.concurrent.TimeUnit;

public class DeadLock {
    public static void main(String[] args) {
        ThreadRunA threadA = new ThreadRunA();
        threadA.setName("thread-A");
        ThreadRunB threadB = new ThreadRunB();
        threadB.setName("thread-B");

        threadA.start();
        threadB.start();
    }
}

// 线程 A 执行这个任务
class ThreadRunA extends Thread {
    @Override
    public void run() {
        synchronized (Lock1.class) {
            System.out.println("线程A获取到 Lock1，正在尝试获取 Lock2");

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (Lock2.class) {
                System.out.println("线程A获取到 Lock2");
            }
        }
    }
}

// 线程 B 执行这个任务
class ThreadRunB extends Thread {
    @Override
    public void run() {
        synchronized (Lock2.class) {
            System.out.println("线程B获取到 Lock2，正在尝试获取 Lock1");

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (Lock1.class) {
                System.out.println("线程B获取到 Lock1");
            }
        }
    }
}

// 第一个锁
class Lock1 {}
// 第二个锁
class Lock2 {}